﻿using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using System.Web.Mvc;
using Ecommerce.Models;
using Library;
using Library.Models;
using Library.MVCHelpers;

namespace Ecommerce.Controllers
{
    public class ProductController : BaseController
    {
        // GET: Product
        public async Task<ActionResult> Index(string categoryUrl, string productUrl)
        {
            var categoryUrlInfo = SEOHelper.GetURLInfo(categoryUrl);
            var productUrlInfo = SEOHelper.GetURLInfo(productUrl);

            // Not found
            if (categoryUrlInfo == null || categoryUrlInfo.URLType != URLTypes.ProductCategory ||
                productUrlInfo == null || productUrlInfo.URLType != URLTypes.Product)
            {
                return HttpNotFound();
            }

            using (var db = DatabaseConnector)
            {
                var product = await db.Products.SingleOrDefaultAsync(i => i.Id == productUrlInfo.ModelId);

                // Not found
                if (product == null)
                {
                    return HttpNotFound();
                }

                var model = new ProductViewModel(product);

                ViewBag.ModelCulture = model.ProductCultures.SingleOrDefault(i => i.Culture == NOWCulture.CurrentCulture) ?? model.ProductCultures.First();

                // Update Viewed-count
                product.ViewedCount = product.ViewedCount + 1 ?? 1;

                return View(model);
            }
        }

        public ActionResult Gallery(ProductViewModel product)
        {
            var gallery = product.GetGallery(NOWCulture.CurrentCulture);
            if (gallery == null)
                return null;

            gallery = gallery.Where(i => !i.IsAvatar.HasValue || !i.IsAvatar.Value).ToList();

            return PartialView(gallery);
        }

        public ActionResult Scope(ProductViewModel product)
        {
            var modelCulture = product.ProductCultures.SingleOrDefault(i => i.Culture == NOWCulture.CurrentCulture) ?? product.ProductCultures.First();
            ViewBag.ModelCulture = modelCulture;
            return PartialView(product);
        }

        public ActionResult Specifications(ProductViewModel product)
        {
            if (product.Specifications == null || product.Specifications.Count == 0)
            {
                return null;
            }

            return PartialView(product.SpecificationGroups);
        }
    }
}